<template>
  <block>
    <van-uploader
      :file-list="fileList"
      :max-count="maxCount"
      :multiple="true"
      accept="image"
      @afterRead="afterRead"
      @delete="deleteImage"
    />
  </block>
</template>

<script>
import { getConfig, uploadImage } from '@requests/oss'
import { compressImage, getParam } from '@utils/index'
import md5 from 'js-md5'
export default {
  name: 'Car',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    maxCount: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      isCompress: true,
      config: {},
      fileList: []
    }
  },
  watch: {
    fileList() {
      this.$emit('input', this.fileList)
    }
  },
  created() {
    this.fileList = this.value.map(i => {
      return {
        ...i,
        status: 'done'
      }
    })
  },
  methods: {
    async getUploadConfig() {
      const config = this.$store.state.oss.config
      if (config && config.expire * 1000 > +new Date()) {
        return config
      }
      const res = await getConfig({ file_type: 'image', project: 'haier' })
      this.$store.commit('oss/setConfig', res.result)
      return res.result
    },
    async upload(file) {
      let filePath = file.path
      if (this.isCompress) {
        filePath = (await this.compress(file)).tempFilePath
      }
      const config = await this.getUploadConfig()
      const {
        host,
        accessid,
        token,
        acl,
        callback,
        policy,
        signature,
        dir
      } = config
      const formData = {
        key:
          dir +
          md5(filePath) +
          '.' +
          file.path
            .split('.')
            .pop()
            .toLowerCase(),
        OSSAccessKeyId: accessid,
        'x-oss-security-token': token,
        'x-oss-object-acl': acl,
        callback,
        policy,
        signature,
        success_action_status: 200
      }
      try {
        const res = await uploadImage({
          url: host,
          filePath: filePath,
          name: 'file',
          formData
        })
        this.uploadSuccess({
          ...file,
          path: res.result.url
        })
      } catch (e) {
        console.log(e)
      }
    },
    uploadSuccess(file) {
      this.fileList = this.fileList.map(item => {
        if (item.key === file.key) {
          return {
            ...file,
            status: 'done'
          }
        }
        return item
      })
    },
    async compress(file) {
      const res = await compressImage({
        src: file.path,
        quality: 70
      })
      return res
    },
    afterRead(e) {
      const { file } = e.detail
      file.forEach(item => {
        const temp = {
          ...item,
          key: Math.random(),
          status: 'uploading'
        }
        this.fileList = [...this.fileList, temp]
        this.upload(temp)
      })
    },
    deleteImage(e) {
      this.fileList.splice(e.detail.index, 1)
      this.fileList = [...this.fileList]
    }
  }
}
</script>
